package com.example.shopdemo.controller.wechat;

import com.example.shopdemo.dto.WechatAuthExecution;
import com.example.shopdemo.entity.PersonInfo;
import com.example.shopdemo.entity.UserAccessToken;
import com.example.shopdemo.entity.WechatAuth;
import com.example.shopdemo.entity.WeiXinUser;
import com.example.shopdemo.enums.WechatAuthStateEnum;
import com.example.shopdemo.repository.PersonInfoRepository;
import com.example.shopdemo.service.WechatAuthServiceImpl;
import com.example.shopdemo.utils.WeiXinUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * @author ：Anitaxiaofeng
 * @description：获取关注公众号之后的微信用户信息的接口，如果在微信浏览器里访问https://open.weixin.qq.com/connect/
 * oauth2/authorize?appid=appId&redirect_uri=http://ip:port/wechat/logincheck&role_type=1&response_type=code
 * &scope=snsapi_userinfo&state=1#wechat_redirect 则这里将会获取到code，之后再可以通过code获取到access_token进而获取到用户信息
 * (redirect_uri就是返回信息自己要写的接口回调接口，然后后面这些参数就是request.getParameter可以获取到的参数，可以理解为
 * 输入上面的url就会调用下面这个logincheck的方法并且带code值，以及后面这些参数)
 * @create 2018-01-31
 **/
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WeiXinLoginController {

    private static final String FRONTEND = "1";
    private static final String SHOPEND = "2";
    @Autowired
    private WechatAuthServiceImpl wechatAuthService;
    @Autowired
    private PersonInfoRepository personInfoRepository;

    @RequestMapping(value = "/logincheck",method = {RequestMethod.GET})
    public String doGet(HttpServletRequest request, HttpServletResponse response){
        log.debug("weixin login get...");
        //获取微信公众号传输过来的code，通过code可获取access_token,进而获取用户信息
        String code = request.getParameter("code");
        log.debug("weixin login code:{}",code);
        String roleType = request.getParameter("state");
        String openId = null;
        WeiXinUser user = null;
        WechatAuth wechatAuth = null;
        if(null!=code){
            UserAccessToken token;
            try{
                //通过code获取access_token
                token = WeiXinUserUtil.getUserAccessToken(code);
                //通过token获取access_token
                String accessToken = token.getAccessToken();
                //通过token获取openId
                openId = token.getOpenId();
                //通过access_token和openId获取用户昵称等信息
                user =WeiXinUserUtil.getUserInfo(accessToken,openId);
                request.getSession().setAttribute("openId",openId);
                wechatAuth = wechatAuthService.getWechatAuthByOpenId(openId);
            }catch(IOException e){
                log.error("error in getUserAccessToken or getUserInfo");
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            }
        }

        //TODO 判断openId是否有以及personInfo的类的生成
        if(wechatAuth==null){
            PersonInfo personInfo = WeiXinUserUtil.getPersonInfoFromRequest(user);
            wechatAuth = new WechatAuth();
            wechatAuth.setOpenId(openId);
            if(FRONTEND.equals(roleType)){
                personInfo.setUserType(1);
            }else{
                personInfo.setUserType(2);
            }
            WechatAuthExecution wechatAuthExecution = wechatAuthService.register(wechatAuth,personInfo);
            if(wechatAuthExecution.getState()!= WechatAuthStateEnum.SUCCESS.getKey()){
                return null;
            }else{
                PersonInfo personInfoResult = personInfoRepository.findByUserId(wechatAuthExecution.getWechatAuth().getUserId());
                request.getSession().setAttribute("user",personInfo);
            }
        }
        //若用户点击的是前端展示系统按钮，则进入前端展示系统
        if(FRONTEND.equals(roleType)){
            return "dashboard/index";
        }else{
            return "shop/shoplist";
        }
    }
}
